package com.ningjingjing.servlet;

import com.ningjingjing.DBUtil;
import com.ningjingjing.model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.security.MessageDigest;
import java.sql.*;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    @Override
    /*
    1.读取用户信息
    2.在存储中进行数据保存
    3.完成登录（Session中保存当前登陆用户信息）
    4.引导浏览器回到首页（重定向）
     */
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String username = req.getParameter("username");
        String nickname = req.getParameter("nickname");
        String password = req.getParameter("password");

        try {
            User user = save(username, nickname, password);

            HttpSession session = req.getSession();
            session.setAttribute("currentUser", username);

            resp.sendRedirect("/");
        } catch (SQLException sqlException) {
            throw new ServletException(sqlException);
        }
    }

        private User save (String username, String nickname, String password) throws SQLException {

        password = hash(password);

            try (Connection c = DBUtil.getConnection()) {
                String sql = "INSERT INTO user (username, nickname, password) VALUES (?, ?, ?)";
                try (PreparedStatement s = c.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
                    s.setString(1, username);
                    s.setString(2, nickname);
                    s.setString(3, password);

                    s.executeUpdate();

                    try (ResultSet resultSet = s.getGeneratedKeys()) {
                        if (!resultSet.next()) {
                            return null;
                        } else {
                            User user = new User();
                            user.username = username;
                            user.nickname = nickname;
                            user.uid = resultSet.getInt(1);
                            return user;
                        }
                    }
                }
            }
        }

    private String hash(String password) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");

            byte[] bytes = password.getBytes("UTF-8");
            byte[] digest = messageDigest.digest(bytes);
            StringBuilder sb = new StringBuilder();
            for (byte b : digest) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();

        }  catch (Exception exc) {
            return password;
        }
    }
}
